from rest_framework import serializers
from books.serializers import BookSerializer
from .models import Borrowing

class BorrowingSerializer(serializers.ModelSerializer):
    book = BookSerializer(read_only=True)
    book_id = serializers.IntegerField(write_only=True)
    borrower = serializers.StringRelatedField(read_only=True)
    borrower_id = serializers.IntegerField(write_only=True)
    status_display = serializers.CharField(source='get_status_display', read_only=True)
    is_overdue = serializers.BooleanField(read_only=True)
    fine = serializers.DecimalField(max_digits=10, decimal_places=2, read_only=True)

    class Meta:
        model = Borrowing
        fields = ['id', 'book', 'book_id', 'borrower', 'borrower_id', 
                  'borrow_date', 'due_date', 'return_date', 
                  'status', 'status_display', 'is_overdue', 
                  'fine', 'notes']
        read_only_fields = ['id', 'borrow_date', 'status_display', 'is_overdue', 'fine']

    def validate(self, data):
        """验证借阅数据"""
        book_id = data.get('book_id')
        borrower_id = data.get('borrower_id')

        # 检查图书是否存在且可借阅
        if book_id:
            try:
                book = Book.objects.get(id=book_id)
                if not book.is_available():
                    raise serializers.ValidationError("该图书当前不可借阅")
            except Book.DoesNotExist:
                raise serializers.ValidationError("图书不存在")

        # 检查用户是否已有未归还的图书
        if borrower_id and not self.instance:  # 创建新记录时检查
            from django.db.models import Q
            active_borrowings = Borrowing.objects.filter(
                borrower_id=borrower_id, 
                return_date__isnull=True
            ).count()

            # 假设每个用户最多只能借5本书
            if active_borrowings >= 5:
                raise serializers.ValidationError("您已达到借阅上限（5本）")

        return data
    
    
class BorrowingListSerializer(serializers.ModelSerializer):
    """借阅列表序列化器，只包含必要信息"""
    book = serializers.StringRelatedField(read_only=True)
    borrower = serializers.StringRelatedField(read_only=True)
    status_display = serializers.CharField(source='get_status_display', read_only=True)

    class Meta:
        model = Borrowing
        fields = ['id', 'book', 'borrower', 'borrow_date', 
                  'due_date', 'return_date', 'status', 'status_display']
